<style scoped>
.post-form{
    margin: 50px auto;
    padding: 30px;
}
.alert{
    margin-top: 10px;
}
</style>

<template>
    <div class="card col-8 post-form">
        <h3 class="text-center">发布新文章</h3>
        <hr>
        <form @submit.prevent="store">
            <div class="form-group">
                <label for="title">标题</label>
                <input type="text" ref="title" class="form-control" id="title" v-model="article.title">
                <div class="alert alert-danger" role="alert" v-show="errors.title"></div>
            </div>
            <div class="form-group">
                <label for="title">标题</label>
                <input type="text" ref="title" class="form-control" id="title" v-model="article.title">
                <div class="alert alert-danger" role="alert" v-show="errors.title"></div>
            </div>
            <div class="form-group">
                <label for="title">标题</label>
                <input type="text" ref="title" class="form-control" id="title" v-model="article.title">
                <div class="alert alert-danger" role="alert" v-show="errors.title"></div>
            </div>
        </form>
    </div>
</template>

<script>
import axios from 'axios';
export default{
    data() {
        return {
            article: {
                title: "",
                author: "",
                content: ""
            },
            errors: {
                title:"",
                author:"",
                contnet: "",
            },
            published:false
        }
    },
    methods:{
        store() {
            //先清理错误消息
            Object.entries(this.errors).forEach(error => {
                let[key,msg]=error;
                this.errors[key] = "";
            });
            axios.post("/post",this.article).then(response=>{
                //请求成功
                this.published =true;
                console.log(response.data);
            }).catch(error=>{
                //请求失败
                //获得验证错误包
                let errorBag = error.response.data;
                //错误包中每个字段的错误信息可能有多个
                Object.entries(errorBag.error).forEach(bag=>{
                    let [field,errors]=bag;
                    if(errors.lenght>0){
                        this.errors[field] = errors.join('<br>');
                    }
                })
            })
        }
    }
}
</script>
